package com.businessportal.web.controllers.authenticate;

import com.businessportal.web.common.AuthHelper;
import com.businessportal.web.common.CryptoHelper;
import com.businessportal.web.common.EmailValidator;
import com.businessportal.web.common.exceptions.AddUserException;
import com.businessportal.web.common.longtask.LongTasker;
import com.businessportal.web.common.longtask.tasks.EmailTask;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.services.UserService;
import com.businessportal.web.notifications.email.MailGunClient;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by Vadim on 11/20/14.
 */
@WebServlet(urlPatterns = "/securepages/register_user.do")
public class RegisterController  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getServletContext().getRequestDispatcher("/securepages/register_user.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try
        {
            String email = req.getParameter("email");
            String name = req.getParameter("name");
            String passw0 = req.getParameter("password0");
            String passw1 = req.getParameter("password1");

            boolean isError = false;
            if (null == email || email.isEmpty())
            {
                req.setAttribute("ErrorEmail", "Field Login is empty!");
                isError = true;
            }

            EmailValidator emailValidator = new EmailValidator();
            if(!emailValidator.validate(email)){
                req.setAttribute("ErrorEmail", "Email is not valid!");
                isError = true;
            }

            if(!UserService.INSTANCE.IsUserNameAcceptable(email)){
                req.setAttribute("ErrorEmail", "Email already used!");
                isError = true;
            }

            if(null == passw0 || passw0.isEmpty())
            {
                req.setAttribute("ErrorPassw0", "First Password is empty!");
                isError = true;
            }
            if(null == passw1 || passw1.isEmpty())
            {
                req.setAttribute("ErrorPassw1", "Repeated Password is empty!");
                isError = true;
            }
            if(null != passw0 && null != passw1 && !passw0.equals(passw1)){
                req.setAttribute("ErrorPassw0", "Passwords are not equal!");
                req.setAttribute("ErrorPassw1", "Passwords are not equal!");
                isError = true;
            }

            if(isError)
            {
                req.getRequestDispatcher("/securepages/register_user.jsp").forward(req, resp);
                return;
            }
            else
            {
                Login user = UserService.INSTANCE.AddNewUser(email, passw0, name);

                if(null == user)
                    throw new AddUserException("New user '" + email + "' - could not created");

                String token = CryptoHelper.getInstance().encodeToHex(user.getLogin());

                String link = req.getScheme() + "://" + req.getServerName().toLowerCase() + "/securepages/email_confirmation.do?token=" + token;

                LongTasker.Execute(new EmailTask(user.getLogin(),
                        "Email confirmation",
                        "You registered on the our portal. <br/><br/>You should confirm your email address. <br/><br/>Use this link: <p><a href='" + link + "'>" + link + "</a></p>"
                ));

                req.removeAttribute("ErrorEmail");
                req.removeAttribute("ErrorPassw0");
                req.removeAttribute("ErrorPassw1");

                req.getRequestDispatcher("/securepages/email_confirmation.jsp").forward(req, resp);

                return;
            }

        }
        catch(AddUserException e){
            System.out.println(e.getMessage());
            req.setAttribute("ErrorSummary", e.getMessage());
        }
        catch (Exception e){
            System.out.println(e.getMessage());
            req.setAttribute("ErrorSummary", "Something went wrong");
        }

        req.getRequestDispatcher("/securepages/register_user.jsp").forward(req, resp);
        return;
    }
}
